import logging

from pylons import config, request, response, session, tmpl_context as c
from pylons.controllers.util import abort
try:
    from pylons.controllers.util import redirect_to
except:
    from pylons.controllers.util import redirect as redirect_to

from serverengine.lib.base import BaseController, render
from serverengine.lib import helpers
from serverengine.model.meta import Session, TUser

log = logging.getLogger(__name__)

class SessionsController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py
    # file has a resource setup:
    #     map.resource('session', 'sessions')
    
    def __before__(self):
        response.headers['content-type'] = 'text/xml; charset=utf-8'
        if 'feedback' not in session:
            session['feedback'] = []
            session.save()
        c.app_name = config['app_name']
        c.app_vers = config['app_vers']
        c.app_base = config['app_base']
    
    def index(self, format='html'):
        """GET /sessions: All items in the collection"""
        # url('sessions')
        if 'identifier' in request.params:
            """
            When 'identifier' is requested, this will respond as a JavaScript file.
            """
            response.headers['content-type'] = 'text/javascript; charset=utf-8'
            c.usersite = config['usersite']
            c.upldquota = config['uploadquota']
            c.quotasize = config['quotasize']
            c.username = ''
            c.realname = ''
            if helpers.hasAuthorization() and not session['user']['username'] == config['admin_username']:
                c.username = session['user']['username']
                c.realname = session['user']['realname']
                log.debug("Authorized Session for %s (%s)" % (session['user']['username'], session['user']['realname']))
            return render('response/session.js')
        else:
            response.headers['content-type'] = 'text/html; charset=utf-8'
            c.feedback = '</p><p>'.join(session['feedback'])
            del session['feedback']
            session.save()
            if helpers.hasAuthorization():
                log.debug("Admin access: Authotized")
                redirect_to('/users')
            else:
                log.debug("Admin access: Denied")
                return render('interface/sessions.login.html')

    def create(self):
        """POST /sessions: Create a new item"""
        # url('sessions')
        user = None
        isAdminAccess = 'admin_access' in request.params
        
        try:
            user = helpers.grantAccessTo(request.params['authID'], request.params['password'], isAdminAccess)
        except:
            message = "Missing required information"
            log.warn(message)
            raise Exception(message)
            abort(403)
            
        if user:
            c.realname = user['realname']
            c.username = user['username']
            log.debug("Authorized Session for %s (%s)" % (c.realname, c.username))
            if isAdminAccess:
                response.headers['content-type'] = 'text/html; charset=utf-8'
                redirect_to('/sessions')
            else:
                response.headers['content-type'] = 'text/xml; charset=utf-8'
                return render("/response/auth-ok.xml")
        else:
            message = "Invalid username or password"
            log.warn(message)
            if isAdminAccess:
                session['feedback'].append(message)
                redirect_to('/sessions')
            else:
                abort(403)

    def new(self, format='html'):
        """GET /sessions/new: Form to create a new item"""
        # url('new_session')

    def update(self, id):
        """PUT /sessions/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('session', id=ID),
        #           method='put')
        # url('session', id=ID)

    def delete(self):
        """DELETE /sessions: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('session', id=ID),
        #           method='delete')
        # url('session', id=ID)
        isAdminAccess = 'admin_access' in request.params
        
        if helpers.denyAccess():
            if isAdminAccess:
                redirect_to(controller = 'sessions', action = 'index')
            else:
                abort(200)
        else:
            log.warn("Session expired")
            abort(200)

    def show(self, id, format='html'):
        """GET /sessions/id: Show a specific item"""
        # url('session', id=ID)

    def edit(self, id, format='html'):
        """GET /sessions/id/edit: Form to edit an existing item"""
        # url('edit_session', id=ID)
